package com.wnhz.trim.plan.service.controller;

import com.wnhz.trim.common.result.HttpResp;
import com.wnhz.trim.domain.entity.Picture;
import com.wnhz.trim.plan.service.service.PictureSrevice;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.Base64;



@RestController
@RequestMapping("/images")
public class PictureController {
    @Autowired
    private PictureSrevice pictureSrevice;



    @ApiOperation(value = "imageUpload", tags = "上传图片接口")
    @PostMapping("/imageUpload")
    public ResponseEntity<String> imageUpload(@RequestParam("file") MultipartFile file) {
        // 以下代码将根据你的数据库和操作方式进行修改

        if (file.isEmpty()) {
            return ResponseEntity.badRequest().body("上传文件为空");
        }

        try {
            // 获取文件内容并转换为字节数组
            byte[] imageData = file.getBytes();
            String base64Image = Base64.getEncoder().encodeToString(imageData);


            // 获取文件名
            String fileName = file.getOriginalFilename();

            // 创建一个实体对象并设置相关属性
            Picture P1 =new Picture();

            P1.setData(base64Image);
            P1.setFileName(fileName);

            // 插入数据到数据库

            pictureSrevice.addPicture(P1); // imageMapper是你的MyBatis Plus Mapper

            return ResponseEntity.ok("图片上传成功");
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("上传失败");
        }
    }


}
